<template>
  <div class="dashboard-container">
    <!-- 搜索栏 -->
    <div class="search">
      <el-form ref="form" :model="params" label-position="top" size="medium">
          <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="名称">
                            <el-input placeholder="请输入名称" v-model="params.name" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="资产类型">
                            <el-select 
                                filterable 
                                clearable
                                v-model="params.propertyType" 
                                placeholder="请选择" 
                                style="width: 100%;"
                            >
                                <el-option v-for="item,index in TARGET_TYPE_LIST" :key="index" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="公司业务类型">
                            <el-select 
                                filterable 
                                v-model="params.customerCompanyBusinessEiid" 
                                placeholder="请选择" 
                                style="width: 100%;"
                            >
                                <el-option v-for="item,index in ustomerCompanyBusinessEiidList" :key="index" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="公司">
                        <el-cascader
                          clearable
                          style="width: 100%;"
                          v-model="customerCompanyId"
                          :options="companyList"
                        >
                        </el-cascader>
                      </el-form-item>
                    </el-col>
          </el-row>
      </el-form>
    </div>
    <div class="opt">
      <el-button type="primary" @click="handleAdd('create')">
          <i class="el-icon-plus"></i>
          创建
      </el-button>
      <el-button type="primary" plain @click="handleSearch">
          <i class="el-icon-search"></i>
          查询
      </el-button>
      
    </div>

    <!-- 列表 -->
    <el-table :data="list">
        <el-table-column label="模板名称" prop="name"></el-table-column>
        <el-table-column label="资产类型" prop="propertyTypesName"></el-table-column>
        <el-table-column label="公司业务类型" prop="customerCompanyBusinessEiidsName"></el-table-column>
        
        <el-table-column label="操作">
            <template slot-scope="{row}">
                <el-button type="text" @click="handleAdd('update', row)">编辑</el-button>
                <el-button type="text" style="color: red;" @click="handleDelete(row.id)">删除</el-button>
                <el-button type="text" v-if="row.dataTemplateUrl" ><a :href="`javascript:POBrowser.openWindow('${API_BASE_URL}/pageOffice/openOSSFile?filePath=${row.dataTemplateUrl}&editFlag=1&fileTitle='+ encodeURIComponent('数据模板'), 'width=1200px;height=900px;');`">打开数据模板</a></el-button>
                <el-button type="text" v-if="row.docTemplateUrl" ><a :href="`javascript:POBrowser.openWindow('${API_BASE_URL}/pageOffice/openOSSFile?filePath=${row.docTemplateUrl}&editFlag=1&fileTitle='+ encodeURIComponent('文档模板'), 'width=1200px;height=900px;');`">打开文档模板</a></el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pageIndex+1"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="params.pageCount"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
    </div>      

    <!-- 新增\编辑 -->
    <el-dialog 
      :title="dialogType=='create'?'新增模板':'编辑模板'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      @close="dialogVisible=false"
      width="800px"
    >
      <el-form ref="form"  :rules="rules" :model="temp" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input placeholder="请输入名称" v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="资产类型" prop="propertyTypes">
          <el-select 
            filterable 
            clearable
            v-model="temp.propertyTypes" 
            placeholder="请选择" 
            style="width: 100%;"
            multiple
          >
            <el-option v-for="item,index in TARGET_TYPE_LIST" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司" prop="customerCompanyIds">
            <el-cascader
              clearable
              style="width: 100%;"
              v-model="temp.customerCompanyIds"
              :options="companyList"
              :props="{multiple: true}"
            >
            </el-cascader>
        </el-form-item>
        <el-form-item label="公司业务类型" prop="customerCompanyBusinessEiids">
          <el-select 
            filterable 
            clearable
            v-model="temp.customerCompanyBusinessEiids" 
            placeholder="请选择" 
            style="width: 100%;"
            multiple
          >
            <el-option v-for="item,index in ustomerCompanyBusinessEiidList" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input placeholder="请输入描述" v-model="temp.description"></el-input>
        </el-form-item>
        <el-form-item label="排序值" prop="sortValue">
          <el-input placeholder="请输入排序值" v-model="temp.sortValue"></el-input>
        </el-form-item>
        <el-form-item label="数据模板：">
            <span v-if="temp.dataTemplateName" style="margin-right: 10px;cursor: pointer;" @click="downloadFile(temp.dataTemplateUrl, temp.dataTemplateName)">
              {{temp.dataTemplateName}}
            </span>
            <el-upload
              class="upload-demo"
              :action="OSS_CONFIG.host"
              :before-upload="(file)=>hanldeUpload(file, 'dataTemplateName')"
              :on-success="()=>handleAvatarSuccess('dataTemplateUrl')"
              :data="uploadData"
              :show-file-list="false">
                
                <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>
        <el-form-item label="文档模板：">
            <span v-if="temp.docTemplateName" style="margin-right: 10px;cursor: pointer;" @click="downloadFile(temp.docTemplateUrl, temp.docTemplateName)">
              {{temp.docTemplateName}}
            </span>
            <el-upload
              class="upload-demo"
              :action="OSS_CONFIG.host"
              :before-upload="(file)=>hanldeUpload(file, 'docTemplateName')"
              :on-success="()=>handleAvatarSuccess('docTemplateUrl')"
              :data="uploadData"
              :show-file-list="false">
                <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submit('form')">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
         </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { fieldGetFieldTemplatePath, fieldAsyncRefreshTemplateFields } from '@/api/field'
import { inquiryTemplateGetList, inquiryTemplateUpdate, inquiryTemplateCreate, inquiryTemplateDelete } from '@/api/inquiryTemplate'
import { OBJECT_ALL_TYPE_LIST, API_BASE_URL, TARGET_TYPE_LIST, OSS_BASE_URL } from '@/utils/common'
import { companyGetTree } from '@/api/company'
import { transfromData, downloadFile, treeTransForm } from '@/utils/tools'
import { enumInfo } from '@/api/enum'
import { commonGetUploadFilePolicy } from '@/api/common'

export default {
  name: 'Template',
  data() {
    return {
        OSS_BASE_URL,
        API_BASE_URL,
        api_url: '',
        OBJECT_ALL_TYPE_LIST,
        TARGET_TYPE_LIST,
        list: [],
        total: 0,
        params: {
          customerCompanyBusinessEiids: '',
          customerCompanyIds: '',
          enabled: '',
          name: '',
          pageCount: 10,
          pageIndex: 0,
          propertyType: ''
        },
        customerCompanyId: [],
        ustomerCompanyBusinessEiidList: [],
        companyList: [],
        dialogType: 'create',
        dialogVisible: false,
        rules: {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          propertyTypes: [{ required: true, message: '请选择资产类型', trigger: 'blur' }],
          customerCompanyIds: [{ required: true, message: '请选择公司', trigger: 'blur' }],
          customerCompanyBusinessEiids: [{ required: true, message: '请选择公司', trigger: 'blur' }],
        },
        temp: {},
        OSS_CONFIG: {
          accessid: '',
          dir: '',
          expire: '',
          host: '',
          policy: '',
          signature: ''
        },
        uploadData: {}
    }
  },
  async mounted() {
    

    //获取公司列表
    let data = await companyGetTree({ userType: 2 })
      //默认最高5级
    this.companyList = treeTransForm(data)
    
    //获取业务列表
    let yewuType = await enumInfo({ id: 36 })
    this.ustomerCompanyBusinessEiidList = yewuType.items.filter(item=>item.selectFlag==1).map(item=>{
        let name = item.name;
        let nowItem = JSON.parse(JSON.stringify(item));
        for(let i=1;i<item.level;i++){
          let parent =  yewuType.items.filter(aItem=>aItem.id==nowItem.parentId);
          if(parent.length>0){
            name = parent[0].name + '-' + name
          }
          nowItem = parent;
        }
        return { label: name, value: item.id }
    })

    this.getData();
    this.getOssConfig();
  },
  methods: {
    downloadFile(url, name){
      downloadFile(url, name);
    },
    //点击删除模板
    handleDelete(id){
      this.$confirm('此操作将永久删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await inquiryTemplateDelete({ ids: [id] })
        this.getData();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //文件上传成功
    handleAvatarSuccess(name){
      this.temp[name] = this.uploadData.key
    },
    //删除钩子
    handleRemove(file){
      // this.temp.files = this.temp.files.filter(item=>{
      //   return item.indexOf(file.uid)==-1
      // })
    },
    //图片上传前，签名处理
    hanldeUpload(file, type){
      this.temp[type] = file.name;
      let fileName = file.uid + '.' + file.name.split('.')[1]
      this.uploadData.name = fileName
      this.uploadData.key = this.OSS_CONFIG.dir + fileName
    },
    //获取Oss详情
    async getOssConfig(){
            let data = await commonGetUploadFilePolicy();
            this.OSS_CONFIG = data;
            this.uploadData = {
                policy: data.policy,
                OSSAccessKeyId: data.accessid,
                success_action_status: '200',
                signature: data.signature,
                key: data.dir,
                name: ''
            }
    },
    //提交表单
    submit(formName){
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
            let temp = JSON.parse(JSON.stringify(this.temp))
            if(temp.customerCompanyIds.length>0){
              temp.customerCompanyIds = temp.customerCompanyIds.map(item=>item[item.length-1])
            }
            if(this.dialogType =='create'){
              await inquiryTemplateCreate(temp)
              this.$message.success('创建成功')
            }else{
              await inquiryTemplateUpdate(temp)
              this.$message.success('修改成功')
            }
            this.handleSearch();
            this.dialogVisible = false;
          } else {
            console.log('error submit!!');
            return false;
          }
      });
    },
    // 点击新增编辑
    handleAdd(type, row){
      this.dialogType = type;
      this.dialogVisible = true;
      if(type=='create'){
        this.temp = {
          customerCompanyBusinessEiids: [],
          customerCompanyIds: [],
          dataTemplateUrl: '',
          docTemplateName: '',
          dataTemplateName: '',
          description: '',
          docTemplateUrl: '',
          name: '',
          propertyTypes: [],
          sortValue: ''
        }
      }else{
         this.temp = row
         console.log(this.temp)
      }
      
    },
    // //树结构数据转化
    // treeTransForm(arr){
    //   return arr.map(item=>{
    //     let children = null;
    //     if(item.companies.length>0){
    //       children = this.treeTransForm(item.companies)
    //     }
    //     return { label: item.name, value: item.id, children }
    //   })
    // },
    //获取客户公司业务类型列表
    async getEiidList(){
      
    },
    // 初始化搜索
    handleSearch(){
      this.params.pageIndex = 0;
      this.getData();
    },
    // 同步字段
    async refresh(row){
        let params = {
            objectType: row.objectType,
        }
        if(row.propertyType){
            params.propertyType = row.propertyType
        }
        await fieldAsyncRefreshTemplateFields(params)
        this.$message.success({message: '刷新成功'})
    },
    
    //获取数据
    async getData(){
        this.params.customerCompanyId = this.customerCompanyId.length>0?this.customerCompanyId[this.customerCompanyId.length-1]:''
        let data = await inquiryTemplateGetList(this.params)
        this.list = data.list.map(item=>{
          item.customerCompanyBusinessEiids = item.customerCompanyBusinessEiids.split(',').map(item=>Number(item));
          item.customerCompanyBusinessEiidsName = item.customerCompanyBusinessEiids.map(item=>{
            return transfromData(this.ustomerCompanyBusinessEiidList, item);
          }).join(',');

          item.propertyTypes = item.propertyTypes.split(',').map(item=>Number(item));
          item.propertyTypesName = item.propertyTypes.map(item=>{
            return transfromData(TARGET_TYPE_LIST, item);
          }).join(',');

          item.customerCompanyIds = item.customerCompanyIds.split(',').map(item=>{
            let arr = [];
            this.companyList.forEach(comItem=>{
              //默认公司只有三级，多级后面再说
              if(comItem.value==item){
                arr.push(item)
              }
              if(comItem.children){
                comItem.children.forEach(childItem=>{
                  if(childItem.value==item){
                    arr.push(comItem.value)
                    arr.push(item)
                  }
                  if(childItem.children){
                    childItem.children.forEach(thirdItem=>{
                      if(thirdItem.value==item){
                        arr.push(comItem.value)
                        arr.push(childItem.value)
                        arr.push(item)
                      }
                    })
                  }
                })
              }
              
            })
            return arr;
          })
          return item;
        })
        this.total = data.totalCount
    },

    // 修改每页数量
    handleSizeChange(val){
        this.params.pageIndex = 0;
        this.params.pageCount = val;
        this.getData();
    },
    // 切换分页
    handleCurrentChange(val){
        this.params.pageIndex = val - 1;
        this.getData();
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
    position: relative;
    .opt{
      margin-bottom: 10px;
    }

    .page {
      padding: 20px 0;
      text-align: center;
    }
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>